import asyncio
from asyncio import sleep, create_task, CancelledError
import time


async def demo1():
    try:
        print("demo1() before")
        await sleep(2)
    except CancelledError:
        print("demo1() sleep canceled")
    print("demo1()")


async def demo2():
    try:
        print("demo2() before")
        await sleep(1)
    except CancelledError:
        print("demo2() sleep canceled")
    print("demo2()")


async def demo2_use():
    await demo2()
    print("=="*10)
    await demo2()


async def task_demo():
    print("="*20)
    task1 = create_task(demo1())
    task2 = create_task(demo2())
    print("="*20)
    # time.sleep(20) # 这个时候 demo1 和 demo2 都没有启动
    await sleep(2)  # await 启动了 demo1 和 demo2
    print("start task1")
    task1.cancel()
    print("end task1")
    task2.cancel()
    print("="*20)

    await sleep(2)  # await 获得了 cancel 的返回，打印 demo1() sleep canceled 和 demo1()

    try:
        print("start await task1 and task2")
        await task1
        await task2
    except CancelledError:
        print("canceled in main")

if __name__ == '__main__':
    # asyncio.run(demo2_use())
    """
    demo2() before
    demo2()
    ====================
    demo2() before
    demo2()
    """

    asyncio.run(task_demo())
